package com.merge.queue;

import com.merge.constant.FileConstant;
import com.merge.pojo.Data;
import com.merge.pojo.SliceFile;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 切片队列
 */
public class SliceQueue<E> {

    public static final String SLICE_QUEUE_PROFIX = "slice_queue";

    private int size = 0;

    private String name;

    private SliceFile sliceFile;

    //队列监控（0关闭 1开启）；
    public int montitor = 1;

    private ConcurrentLinkedQueue<E> queue;

    public SliceQueue(SliceFile sliceFile) {
        this.sliceFile = sliceFile;
        this.name =  this.sliceFile.getName() + "_" + SLICE_QUEUE_PROFIX;
        queue = new ConcurrentLinkedQueue<E>();
    }

    public boolean offer(E e) {
        boolean result = queue.offer(e);
        if (result) size++;
        return result;
    }

    public E poll() {
        E item = queue.poll();
        if (item != null) size--;
        return item;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SliceFile getSliceFile() {
        return sliceFile;
    }

    public void setSliceFile(SliceFile sliceFile) {
        this.sliceFile = sliceFile;
    }

    public ConcurrentLinkedQueue<E> getQueue() {
        return queue;
    }

    public void setQueue(ConcurrentLinkedQueue<E> queue) {
        this.queue = queue;
    }

    public String toString() {
        return "name:" + name + " size:" + size + " slice_file:" + sliceFile.getName();
    }
    public static void main(String[] args) {
        String sliceFileName = FileConstant.SLICE_FILE_PROFIX + 1;
        SliceFile sliceFile = new SliceFile(sliceFileName);
        SliceQueue<Data> queue = new SliceQueue<>(sliceFile);
        System.out.println(queue.getName());
        int i = 0;
        while (queue.getSize() <= 10) {
            queue.offer(new Data(i++, queue.getName()));
        }
        while (queue.getSize() > 0) {
            System.out.println(queue.poll().getValue());
        }
    }
}
